<template>
  <div ref="dom" class="charts chart-bar"></div>
</template>

<script>
import echarts from 'echarts'
import { on, off } from '@/libs/tools'
import macarons from './macarons.json'
echarts.registerTheme('macarons', macarons)
export default {
  name: 'ChartBar',
  props: {
    value: Array,
    text: String,
    subtext: String,
    legend: Object
  },
  data () {
    return {
      dom: null
    }
  },
  methods: {
    resize () {
      this.dom.resize()
    },
    render () {
      let xAxisData = this.value.map(item => {
        return item.labCode
      })
      // let seriesData = Object.values(this.value)
      let option = {
        title: {
          text: this.text,
          subtext: this.subtext,
          x: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'horizontal',
          left: 'left',
          data: this.legend.data.map(item => {
            return item.value
          }),
          textStyle: {
            color: 'auto'
          }
        },
        dataZoom: [{
          type: 'inside',
          orient: 'horizontal',
          xAxisIndex: [0],
          startValue: 0,
          endValue: 7
        }],
        xAxis: [{
          type: 'category',
          data: xAxisData
        }],
        yAxis: [{
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        }],
        // series: [{
        //   data: seriesData,
        //   type: 'bar'
        // }]
        series: this.legend.data.map(item => {
          return {
            name: item.value,
            type: 'bar',
            label: {
              normal: {
                show: true,
                position: 'top'
              }
            },
            data: this.value.map(v => {
              return v[item.key]
            }),
            markPoint: {
              data: [
                {type: 'max', name: '最大值'},
                {type: 'min', name: '最小值'}
              ]
            },
            markLine: {
              data: [
                {type: 'average', name: '平均值'}
              ]
            }
          }
        })
      }
      this.$nextTick(() => {
        this.dom = echarts.init(this.$refs.dom, 'macarons')
        this.dom.setOption(option)
        on(window, 'resize', this.resize)
      })
    }
  },
  mounted () {
    this.render()
  },
  beforeDestroy () {
    off(window, 'resize', this.resize)
  },
  watch: {
    value (newValue) {
      this.render()
    }
  }
}
</script>

<style lang="less">
.charts{
  //
}
</style>
